﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Data;
using Newtonsoft.Json;

namespace WebAppMatrix.Extensions
{
    public static class SerializeExtensions
    {
        #region 二进制序列化和反序列化

        public static byte[] SerializeToBytes(this object obj)
        {
            if (obj == null)
                throw new ArgumentNullException("obj");

            MemoryStream ms = new MemoryStream();
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(ms, obj);

            return ms.GetBuffer();
        }

        public static T DeserializeFromBytes<T>(this byte[] bytes)
        {
            if (bytes == null)
                throw new ArgumentNullException("bytes");

            MemoryStream ms = new MemoryStream(bytes);
            BinaryFormatter binaryFormatter = new BinaryFormatter();

            return (T)binaryFormatter.Deserialize(ms);
        }

        #endregion

        #region Json序列化和反序列化

        /// <summary>
        /// 序列化对象为Json字符串
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>Json字符串</returns>
        public static string SerializeToJson(this object obj, int recursionLimit = 100)
        {
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// 反序列化对象
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="value">Json字符串</param>
        /// <returns>目标类型的实例</returns>
        public static T DeserializeFromJson<T>(this string value)
        {
            return JsonConvert.DeserializeObject<T>(value);
        }

        /// <summary> 
        /// DataTable转为json 
        /// </summary> 
        /// <param name="dt">DataTable</param> 
        /// <returns>json数据</returns> 
        public static string ToJson(DataTable dt)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc]);
                }
                list.Add(result);
            }

            return SerializeToJson(list);
        }

        #endregion
    }
}
